package local.pt.iscte.dcti.pa.utils;

import java.util.List;
import java.util.ArrayList;
import org.eclipse.core.runtime.ISafeRunnable;

import com.eexcel.workbench.IFormula;

/**
 * Defines one formula provided by the contributor
 * @author Simão Fernandes
 * @version %I%, %G%
 * @since 1.0
 *
 */
public class FormulaContributor {

	/**s
	 * Name of the contributor
	 */
	private String name;
	/**
	 * Names of the functions the contributor defines
	 */
	private List<String> functions;
	/**
	 * Executable extension instance
	 */
	private IFormula executableExtension;
	/**
	 * function result
	 */
	private int result;

	/**
	 * Default constructor
	 */
	public FormulaContributor() {
		functions = new ArrayList<String>();
	}

	/**
	 * Applies the given function to a given method
	 * 
	 * @param function
	 *            Function to apply to the operand
	 * @param operand
	 *            Operand to be applied
	 * @return Function applying result
	 */
	public int applyFunction(final String function, final int operand) {
		if (!function.contains(function)) {
			// TODO handle exception
		}

		ISafeRunnable runnable = new ISafeRunnable() {
			@Override
			public void handleException(Throwable exception) {
				System.out.println("Exception in client");
			}

			@Override
			public void run() throws Exception {
				setResult(executableExtension.calculate(function, operand));
			}
		};
		org.eclipse.core.runtime.SafeRunner.run(runnable);

		return getResult();
	}

	// GETTERS & SETTERS: start
	/**
	 * Gets the name of the contributor
	 * 
	 * @return Name of the contributor
	 */
	public String getName() {
		return name;
	}

	/**
	 * Sets the name of the contributor
	 * 
	 * @param name
	 *            Name of the contributor
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * Gets the functions of the contributor
	 * 
	 * @return The functions of the contributor
	 */
	public List<String> getFunctions() {
		return functions;
	}

	/**
	 * Sets the the functions of the contributor
	 * 
	 * @param functions
	 *            The functions of the contributor
	 */
	public void setFunctions(List<String> functions) {
		this.functions = functions;
	}

	/**
	 * Gets the executable extension instance
	 * 
	 * @return The executable extension instance
	 */
	public Object getExecutableExtension() {
		return executableExtension;
	}

	/**
	 * Sets the executable extension instance
	 * 
	 * @param executableExtension
	 *            The executable extension instance
	 */
	public void setExecutableExtension(IFormula executableExtension) {
		this.executableExtension = executableExtension;
	}

	/**
	 * Gets the function result
	 * 
	 * @return The function result
	 */
	public int getResult() {
		return result;
	}

	/**
	 * Sets the function result
	 * 
	 * @param result
	 *            The function result
	 */
	private void setResult(int result) {
		this.result = result;
	}
	// GETTERS & SETTERS: end
}
